package com.qianjiangcloud.store.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.MyImageLoader;


/**
 * Created by Jelly on 2016/8/2.
 */
public class AccountSelectGoodFragment extends BaseDoFragment implements View.OnClickListener{
    private String ordetId="";
    private ListView mListView;
    private Button mSubmit;
    private Button mSelectAllBtn;
    private GoodsListAdapter mGoodsListAdapter;
    private LayoutInflater mLayoutInflater;
    private ArrayList<JSONObject> mAllGoods=new ArrayList<JSONObject>();
    private List<JSONObject> mSelectedGoods = new ArrayList<JSONObject>();
    private JSONArray mReasonsList=new JSONArray();
    private DecimalFormat mDecimalFormat = new DecimalFormat("0.00");
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent=mActivity.getIntent();
        if (intent!=null) {
            ordetId = intent.getStringExtra("orderId");
        }
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.init(inflater, container, savedInstanceState);
        mLayoutInflater=inflater;
        mActionBar.setTitle(mActivity.getString(R.string.select_goods));
        rootView=inflater.inflate(R.layout.fragment_after_select_good,null);
        mListView= (ListView) findViewById(R.id.fragment_exchange_listview);
        mSubmit= (Button) findViewById(R.id.fragment_exchange_submit);
        mSelectAllBtn= (Button) findViewById(R.id.fragment_exchange_select_all);
        mGoodsListAdapter = new GoodsListAdapter();
        mListView.setAdapter(mGoodsListAdapter);
        mSelectAllBtn.setOnClickListener(this);
        mSubmit.setOnClickListener(this);
        Run.excuteJsonTask(new JsonTask(),new GetOrderGoodsTask());
    }


    private class GoodsListAdapter extends BaseAdapter implements View.OnClickListener {

        @Override
        public int getCount() {
            return mAllGoods.size();
        }

        @Override
        public JSONObject getItem(int position) {
            return mAllGoods.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = mLayoutInflater.inflate(R.layout.account_after_goods_edit_item, null);
                viewHolder.iconImage = (ImageView) convertView.findViewById(R.id.edit_icon_select);
                viewHolder.goodsImage = (ImageView) convertView.findViewById(R.id.edit_icon);
                viewHolder.goodsNmaeText = (TextView) convertView.findViewById(R.id.edit_name);
                viewHolder.number= (TextView) convertView.findViewById(R.id.good_number);
                viewHolder.price= (TextView) convertView.findViewById(R.id.price);
                viewHolder.spec= (TextView) convertView.findViewById(R.id.tv_spec);
                convertView.setOnClickListener(this);
                viewHolder.iconImage.setOnClickListener(this);
                convertView.setTag(R.id.edit_icon_select,viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag(R.id.edit_icon_select);
            }
            final JSONObject goods = getItem(position);
            convertView.setTag(goods);
        //    JSONObject goods = goodsObject.optJSONObject("goods");
            MyImageLoader.displayDefaultImage(goods.optString("thumbnail_pic_scr"),viewHolder.goodsImage);
            viewHolder.goodsNmaeText.setText(goods.optString("name"));
            boolean isSelected=mSelectedGoods.contains(goods);
            viewHolder.iconImage.setTag(goods);
            viewHolder.iconImage.setImageResource(isSelected ? R.drawable.goods_select:R.drawable.goods_no_select);
            viewHolder.number.setText("x " + goods.optString("quantity"));
            viewHolder.price.setText(mActivity.getString(R.string.shopping_car_price,
                    mDecimalFormat.format(goods.optDouble("price") * goods.optInt("quantity"))));
            try {
                JSONObject produces=goods.getJSONObject("products");
                if(!produces.isNull("spec_info"))
                    viewHolder.spec.setText(produces.optString("spec_info"));

            } catch (JSONException e) {
                e.printStackTrace();
            }


            return convertView;
        }
        @Override
        public void onClick(View view) {
            Object obj=view.getTag();
            if (obj==null){
                return;
            }
            JSONObject data= (JSONObject) obj;
            if (view.getId()==R.id.edit_icon_select) {

                if (mSelectedGoods.contains(data)) {
                    mSelectedGoods.remove(data);
                    ((ImageView) view).setImageResource(R.drawable.goods_no_select);
                } else {
                    mSelectedGoods.add(data);
                    ((ImageView) view).setImageResource(R.drawable.goods_select);
                }
            } else{
                if (mSelectedGoods.contains(data)) {
                    mSelectedGoods.remove(data);
                    ((ImageView)view.findViewById(R.id.edit_icon_select))
                            .setImageResource(R.drawable.goods_no_select);
                } else {
                    mSelectedGoods.add(data);
                    ((ImageView)view.findViewById(R.id.edit_icon_select))
                            .setImageResource(R.drawable.goods_select);
                }
            }

                if (mSelectedGoods.size() == mAllGoods.size()) {
                    setSelectedAllState(true);
                } else {
                    setSelectedAllState(false);
                }



        }
    }

    private class ViewHolder {
        private ImageView iconImage;
        private ImageView goodsImage;
        private TextView goodsNmaeText;
        private TextView price;
        private TextView number;
        private TextView spec;

    }

    @Override
    public void onClick(View v) {
        if (v == mSelectAllBtn) {
            boolean isSelectedAll = mSelectAllBtn.isSelected();
            mSelectedGoods.clear();
            if (!isSelectedAll) {
                mSelectedGoods.addAll(mAllGoods);
            }
            setSelectedAllState(!isSelectedAll);
            mGoodsListAdapter.notifyDataSetChanged();
        } else if(v==mSubmit){
            if (mSelectedGoods==null||mSelectedGoods.size()<1){
                Run.alert(mActivity,"请选择要退换的商品");
                return;
            }
            JSONArray list =new JSONArray();
            for (int i=0;i<mSelectedGoods.size();i++){
                list.put(mSelectedGoods.get(i));
            }
            startActivity(AgentActivity.intentForFragment(mActivity,AgentActivity.FRAGMENT_AFTER_SERVICE_COMMIT)
            .putExtra("orderId",ordetId).putExtra("json",list.toString()).putExtra("reason",mReasonsList.toString()));
        }
    }

    private void setSelectedAllState(boolean isSelectedAll) {
        mSelectAllBtn.setSelected(isSelectedAll);
        mSelectAllBtn.setCompoundDrawablesWithIntrinsicBounds(
                isSelectedAll ? R.drawable.goods_select : R.drawable.goods_no_select, 0, 0, 0);
    }


    public class GetOrderGoodsTask implements JsonTaskHandler {

        @Override
        public void task_response(String json_str) {
            mAllGoods.clear();
            mSelectedGoods.clear();
            try {
                JSONObject all =new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity,all)){
                    JSONObject data=all.optJSONObject("data");
                    JSONObject order=data.optJSONObject("order");
                    JSONObject content=data.optJSONObject("content");
                    mReasonsList=content.optJSONArray("reason");
                    JSONArray items=order.optJSONArray("items");
                    if (items!=null&&items.length()>0){
                        for (int i=0;i<items.length();i++){
                            mAllGoods.add(items.getJSONObject(i));
                        }
                        mSelectedGoods.addAll(mAllGoods);
                        mGoodsListAdapter.notifyDataSetChanged();
                    }


                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }

        @Override
        public JsonRequestBean task_request() {
            JsonRequestBean req=new JsonRequestBean("mobileapi.aftersales.add");
            req.addParams("order_id",ordetId);
            return req;
        }
    }



}
